<script setup>
import { computed, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import logger from '@/utils/logger'
import { postCheckPzReturnGoodsByDealerId } from '@/api/goodsReturnApi'
import { formatDateTime, getNowDateTime } from '@/utils/dayjs'

const props = defineProps({
  modelValue: Boolean,
  form: {
    type: Object,
    default: () => ({
      approved: true,
    }),
  },
  currentItem: {
    type: Object,
    default: null,
  },
  returnTypeOptions: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['update:modelValue', 'close', 'submitted'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

const submitLoading = ref(false)
const formState = ref({})

watch(
  () => props.form,
  (value) => {
    formState.value = { ...value }
  },
  { immediate: true, deep: true },
)

watch(
  () => dialogVisible.value,
  (visible) => {
    if (visible) {
      formState.value = {
        ...formState.value,
        checkTime: getNowDateTime(),
      }
    }
  },
)

const imageList = computed(() => {
  if (!props.currentItem?.imgPaths) return []
  return props.currentItem.imgPaths
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean)
})

const getReturnTypeText = (type) => {
  const option = props.returnTypeOptions.find((item) => item.value === type)
  return option ? option.label : '未知类型'
}

const handleConfirm = async () => {
  if (!props.currentItem) return

  try {
    await ElMessageBox.confirm(
      `确定${formState.value.approved ? '通过' : '拒绝'}该退货申请吗？`,
      '确认审核',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
    await submitAudit()
  } catch {
    // 用户取消操作
  }
}

const submitAudit = async () => {
  try {
    submitLoading.value = true
    const auditData = {
      ...props.currentItem,
      ...formState.value,
      returnPoints: formState.value.approved ? formState.value.returnPoints : 0,
      returnMoney: formState.value.approved ? formState.value.returnMoney : 0,
    }

    const res = await postCheckPzReturnGoodsByDealerId(auditData)
    if (res.success) {
      ElMessage.success('审核完成')
      emit('submitted')
      handleClose()
    } else {
      ElMessage.error(res.msg || '审核失败')
    }
  } catch (error) {
    logger.error('审核失败', error)
    ElMessage.error('审核失败')
  } finally {
    submitLoading.value = false
  }
}

const handleClose = () => emit('close')
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="退货审核"
    width="60%"
    append-to-body
    align-center
    destroy-on-close
    @close="handleClose"
  >
    <div v-if="currentItem" class="audit-container">
      <div class="return-info">
        <h4>退货商品信息</h4>
        <el-descriptions border :column="2" size="small">
          <el-descriptions-item label="商品名称">{{ currentItem.goodsName }}</el-descriptions-item>
          <el-descriptions-item label="订单号">{{ currentItem.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="退货数量">{{
            currentItem.returnQuantity
          }}</el-descriptions-item>
          <el-descriptions-item label="购买数量">{{
            currentItem.purchaseQuantity
          }}</el-descriptions-item>
          <el-descriptions-item label="退货原因">{{
            currentItem.returnReason
          }}</el-descriptions-item>
          <el-descriptions-item label="退货类型">{{
            getReturnTypeText(currentItem.returnType)
          }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ formatDateTime(currentItem.returnTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="可退金额">{{
            currentItem.canReturnpoints
          }}</el-descriptions-item>
        </el-descriptions>

        <div v-if="imageList.length" class="return-images">
          <h5>退货图片：</h5>
          <div class="images-container">
            <el-image
              v-for="(img, index) in imageList"
              :key="`${img}-${index}`"
              :src="img"
              style="width: 100px; height: 100px; margin-right: 10px; border-radius: 4px"
              :preview-src-list="imageList"
              fit="cover"
              preview-teleported
            />
          </div>
        </div>
      </div>

      <div class="audit-form">
        <h4>审核信息</h4>
        <el-form :model="formState" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="审核结果">
                <el-radio-group v-model="formState.approved">
                  <el-radio :value="true">通过</el-radio>
                  <el-radio :value="false">拒绝</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审核时间">
                <el-date-picker
                  v-model="formState.checkTime"
                  type="datetime"
                  placeholder="选择审核时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  disabled
                />
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="formState.approved">
              <el-form-item label="退还金额">
                <el-input-number
                  v-model="formState.returnMoney"
                  :min="0"
                  :max="currentItem?.amount || 0"
                  :precision="2"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="submitLoading">
          确认退款
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.audit-container {
  .return-info {
    margin-bottom: 30px;
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 8px;

    h4 {
      margin-bottom: 20px;
      color: #303133;
    }

    .el-descriptions {
      background: transparent;
    }

    .return-images {
      margin-top: 20px;

      h5 {
        margin-bottom: 10px;
        color: #606266;
      }

      .images-container {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }

  .audit-form {
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 8px;

    h4 {
      margin-bottom: 20px;
      color: #303133;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
